package com.shuzi.MediaShare.control;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

/**
 * 缓存类
 * 
 * @author lung
 * 
 */
public class CacheDataManager
{
	private static CacheDataManager instance;

	private final String TAG = "CacheDataManager";

	public static CacheDataManager getInstance()
	{
		if (instance == null)
		{
			instance = new CacheDataManager();
		}
		return instance;
	}

	/**
	 * 缓存数据到配置文件
	 * 
	 * @param context
	 * @param cacheKey
	 * @param data
	 */
	public void saveCacheDataToSharedPreferences(Context context,
			String cacheKey, String data)
	{
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				cacheKey, Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putString(cacheKey, data);
		editor.commit();
		// DLog.d(TAG, "cacheKey = " + cacheKey + "data = " + data);

	}

	/**
	 * 從配置文件裏面获取缓存数据
	 * 
	 * @param context
	 * @param cacheKey
	 * @return
	 */
	public String getCacheDataToSharedPreferences(Context context,
			String cacheKey)
	{
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				cacheKey, Activity.MODE_PRIVATE);
		// DLog.d(TAG,
		// "cacheKey = " + cacheKey + "data = "
		// + sharedPreferences.getString(cacheKey, ""));
		return sharedPreferences.getString(cacheKey, "");
	}

	/**
	 * 保存缓存数据到文件
	 * 
	 * @param <T>
	 * @param context
	 * @param list
	 * @return
	 */
	public boolean saveCachDataToFile(Context context, String fileName,
			Object object)
	{
		if (object == null)
		{
			return false;
		}
		try
		{
			// 需要一个文件输出流和对象输出流；文件输出流用于将字节输出到文件，对象输出流用于将对象输出为字节
			FileOutputStream fout = context.openFileOutput(fileName + ".ser",
					Activity.MODE_PRIVATE);
			ObjectOutputStream out = new ObjectOutputStream(fout);
			out.writeObject(object);
			out.close();
		} catch (IOException e)
		{
			// DLog.e(e + "");
		}
		return true;
	}

	/**
	 * 从文件里面获取缓存数据
	 * 
	 * @param context
	 * @param fileName
	 * @return
	 */
	public Object getCacheDataToFile(Context context, String fileName)
	{
		Object object = null;
		try
		{
			FileInputStream fin = context.openFileInput(fileName + ".ser");
			ObjectInputStream in = new ObjectInputStream(fin);
			object = in.readObject();
		} catch (Exception e)
		{
			// DLog.e(e + "");
		}

		return object;
	}
	
	

}
